import cn from 'classnames';
import PropTypes from 'prop-types';
import React, { useState } from 'react';
import { gql } from '@apollo/client';
import { withRouter } from 'react-router';
import fetch from 'fermionjs/lib/fetch';
import { searchStringBuilder } from '@kuiper-components/page-table';
import Table from '@knownsec/react-component/dist/Table';
import Pagination from '@knownsec/react-component/dist/Pagination';
import EmptyData from '../../../components/empty/EmptyData';
import { Link } from 'react-router-dom';

import Toolbox from './Toolbox';
import CopyBoard from '../../../components/CopyBoard';
import DownOnce from '../../../components/DownOnce';
import WarningCategoryCount from '../../../components/WarningCategoryCount';
import { datetime } from '../../../../common/formatter';
import ColSecurityStatus from '../../../components/ColSecurityStatus';
import TaskMonitorSetting from '../../../components/TaskSettingsViewer';
import collectType from '../../../../common/collectType';
import Breadcrumb, { Item } from '../../../components/Breadcrumb';
import s from './style.module.css';

const columnsBuilder = () => [
	{
		title: '资产名称',
		dataIndex: 'job',
		key: 'job',
		render(job) {
			return (
				<div className={s.target} title={job?.note}>
					{job?.note}
				</div>
			);
		},
	},
	{
		title: '资产地址',
		dataIndex: 'target',
		key: 'target',
		render(target) {
			return <CopyBoard text={target} maxWidth="12rem" />;
		},
	},
	{
		title: '监测方式',
		dataIndex: 'triggerType',
		key: 'triggerType',
		render(triggerType) {
			return collectType({ triggerType });
		},
	},
	{
		title: '威胁数',
		dataIndex: 'result',
		key: 'count',
		render(result) {
			const data = result?.warnings?.reduce((obj, x) => {
				if (!x?.category) return obj;
				if (!obj[x.category]) {
					obj[x.category] = {
						warningIgnoredCount: 0,
						warningCount: 0,
					};
				}
				obj[x.category].warningCount += 1;
				if (x.ignoredTime) {
					obj[x.category].warningIgnoredCount += 1;
				}
				return obj;
			}, {});
			return <WarningCategoryCount taskType="content" category={data} />;
		},
	},
	{
		title: '安全状态',
		dataIndex: 'securityStatus',
		key: 'securityStatus',
		render(securityStatus, { taskSessionId, taskType }) {
			return (
				<ColSecurityStatus
					taskType={taskType}
					tsid={taskSessionId}
					securityStatus={securityStatus}
				/>
			);
		},
	},
	{
		title: '监测完成时间',
		dataIndex: 'endTime',
		key: 'updateTime',
		width: 200,
		render(endTime) {
			return datetime(endTime);
		},
	},
	{
		title: '操作',
		dataIndex: 'target',
		key: '__actions__',
		width: 100,
		render(target, record) {
			return (
				<div className={s.actions}>
					<Link
						to={{pathname: `/job-manage/web-task/content-detail/${record?._id}`,
						search: `tsid=${record?.taskSessionId}`,
						state: {refer: location?.href.split('?')[1]}}}
						className={s.linkBtn}
					>
						详情
					</Link>
					{/* <TaskMonitorSetting
						className={s.linkBtn}
						host={target}
						taskType={record?.taskType}
						triggerType={record?.triggerType}
						taskSettings={record?.taskSettings}
						isLatestTask={record?.isLatestTask}
						note={record?.job?.note}
						jobId={record?.isLatestTask ? record?.refId : undefined}
						alertSettings={record?.alertSettings}
					>
						配置
					</TaskMonitorSetting> */}
					<DownOnce
						className={s.linkBtn}
						record={{ ...record, note: record?.job?.note }}
					/>
				</div>
			);
		},
	},
];

function History({ className, history, location }) {
	const routePrefix = '/content/content/overview/history';
	const search = new URLSearchParams(location.search);
	const filter = JSON.parse(search.get('filter')) || {};
	const defaultFilter = {
		taskType: 'content',
		OR: [{ securityStatus: 'safe' }, { securityStatus: 'warning' }],
	};

	const {
		triggerType,
		securityStatus,
		endTime_gte,
		endTime_lt,
		targetSearch,
	} = filter;
	const [tableData, setData] = useState([]);
	const [count, setCount] = useState(0);
	const [page, setPage] = useState(1);
	const [loading, setLoading] = useState(false);
	const [type, setType] = useState('empty');
	const [perPage, setPerpage] = useState(10);
	const [otherQuery, setQuery] = useState({
		endTime_lt,
		endTime_gte,
		securityStatus,
		targetSearch,
		triggerType,
	});

	const handleFilterChange = filter => {
		const searchString = searchStringBuilder(location.search, {
			originTarget: search.get('originTarget') || '',
			filter: JSON.stringify({
				...filter,
				taskType: 'content',
			}),
			page: 1,
			sort: 'ENDTIME_DESC',
		});
		const obj = Object.assign({}, filter);
		setPage(1);
		setPerpage(10);
		setQuery(obj);
		history.replace(`${routePrefix}?${searchString}`);
	};

	const tablestate = item => {
		setPerpage(item.perPage || 10);
		setPage(item.page || 1);
		getData(item.page, item.perPage);
	};
	const turnToUrlparam = obj => {
		let urls = '';
		const hasValKey = Object.keys(obj)
			.filter(
				item =>
					obj[item] ||
					obj[item] === false ||
					(typeof obj[item] !== 'string' && obj[item] == 0)
			)
			.map(i => {
				return i + '=' + obj[i];
			});
		urls = hasValKey.join('&');
		return urls;
	};

	const getData = (num, size) => {
		setLoading(true);
		const querydata = Object.assign(
			{
				page: num || 1,
				count: size || 10,
				taskType: 'content',
				status: 'completed',
			},
			otherQuery
		);
		if (!querydata.securityStatus) {
			querydata.securityStatus = 'safe,warning';
		}
		const params = turnToUrlparam(querydata);
		fetch(`/api/v2/result/history?${params}`, {
			method: 'GET',
		})
			.then(res => {
				setLoading(false);
				const { results, total } = res.data;
				setCount(total);
				setData(results);
			})
			.catch(err => {
				setLoading(false);
			})
			.finally(() => {
				setType('img');
			});
	};
	React.useMemo(() => getData(1, 10), [otherQuery]);

	return (
		<div className={cn(className, s.history)}>
			<Breadcrumb className={s.breadcrumb}>
				<Item key="content/content/overview">内容违规监测</Item>
				<Item key="history">历史任务</Item>
			</Breadcrumb>

			<div className={s.tableWrapper}>
				<Toolbox filter={filter} onChange={handleFilterChange} />
				<Table
					pro
					loading={loading}
					empty={<EmptyData type={type} className={s.empty2} />}
					columns={columnsBuilder()}
					data={tableData}
				/>
				{count > 10 && (
					<Pagination
						className={s.pagination}
						pageSizeOptions={[10, 20, 50]}
						showSizeChanger
						showQuickJumper
						showTotal={total => `共${total}条`}
						total={count}
						current={page}
						page={page}
						onChange={(page, pageSize) => {
							tablestate({ perPage: pageSize, page });
						}}
					/>
				)}
			</div>
		</div>
	);
}

History.propTypes = {
	className: PropTypes.string,
	location: PropTypes.shape({
		search: PropTypes.string.isRequired,
	}).isRequired,
	history: PropTypes.shape({
		replace: PropTypes.func.isRequired,
	}).isRequired,
};
History.defaultProps = {
	className: '',
};

export default withRouter(History);
